package com.test.mytest.socket;

import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class SendMessageToDevice {
	public static void main(String[] args) {
		for (int i = 0; i < 1; i++) {
			Socket socket = null;
			try {
				socket = new Socket(InetAddress.getByName("192.168.1.216"), 10001);
				socket.setSoTimeout(5000);
				OutputStream outputStream = socket.getOutputStream();
				outputStream.write(getByte());
				outputStream.flush();
				byte[] b = new byte[11];
				long start = System.currentTimeMillis();
				int hasNext = 0;
				while (true) {
					if (System.currentTimeMillis() - start > 5000) {
						throw new Exception("读取消息超时");
					}
					int read = socket.getInputStream().read(b,hasNext,11);
					System.out.println(read);
					if (read == -1) {
						Thread.sleep(1);
						continue;
					}
					System.out.println(hasNext + "===" + b[hasNext]);
					hasNext += read;
					if (hasNext >= 11) {
						break;
					}
				}
				System.out.println("花费时间：" + (System.currentTimeMillis() - start));
				socket.close();
							for (byte c : b) {
								System.out.println(c+"========="+byteToHexString(c));
							}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
			} 
		}
	}

	private static byte[] getByte() {
		String privilege = "01 57 00 01 00 01 E0 02 78 08 51 E9 00 00 00 00 16 06 23 00 00 19 06 21 14 31 09 03 7E";
		String msg="01 57 00 01 00 01 F0 02 03 A7";
		String[] split = privilege.split(" ");
		byte[] data=new byte[split.length];
		for (int i = 0; i < data.length; i++) {
			int gao=Character.digit(split[i].charAt(0), 16)*16;
			int di=Character.digit(split[i].charAt(1), 16);
			System.out.println(split[i]+"====gao==="+gao+"--------de==="+di);
			data[i]=(byte) (gao+di);
			System.out.println(split[i]+"================================="+data[i]);
		}
		return data;
	}
	public static byte[] hexStringToByteArray(String s) {
        s = s.replaceAll(" ","");
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            int digit = Character.digit(s.charAt(i), 16);
			int j = digit << 4;
			int digit2 = Character.digit(s.charAt(i + 1), 16);
			System.out.println(digit+"===="+j+"==="+digit2);
			data[i / 2] = (byte) (j+ digit2);
        }
        return data;
    }
	
	 public static String byteToHexString(byte bytes) {
	        char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
	                'A', 'B', 'C', 'D', 'E', 'F'
	        };
	        char hexChars1 = 0;
	        char hexChars2 = 0;
	        int v;

	        v = bytes & 0xFF;
	        hexChars1 = hexArray[v / 16];
	        hexChars2 = hexArray[v % 16];

	        return hexChars1 + "" + hexChars2;
	    }
	
}
